import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/date_symbol_data_local.dart' show initializeDateFormatting;
import 'package:oktoast/oktoast.dart';

import 'base/healthpages.dart';
import 'base/constant.dart';
import 'base/eventbus.dart';
import 'base/lang.dart';
import 'base/log.dart';
import 'base/stringres.dart';
import 'database/app_data.dart';
import 'native/nativechannel.dart';

Future<void> _reportError(dynamic error, dynamic stackTrace) async {
  if (!kReleaseMode) {
    debugPrint('catch error=$error,$stackTrace');
  }
}

void main() {
  runZonedGuarded(() {
    FlutterError.onError = (FlutterErrorDetails details) {
      FlutterError.presentError(details);
    };
    initializeDateFormatting().then((_) {
      // 初始化完成后运行应用
      runApp(const MyApp());
    });

    //用来做沉浸式状态栏
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.black,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }, (Object error, StackTrace stackTrace) async {
    await _reportError(error, stackTrace);
  });
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

//初始化系统
initSystem() {
  Native.initMethodResultBack();
  APPDatabase.init();
}

class _MyAppState extends State<MyApp> {
  static const _tag = '[main.dart][_MyAppState]';

  @override
  void initState() {
    super.initState();
    initSystem();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return OKToast(
        child: GetMaterialApp(
            getPages: HealthPages.pages,
            initialRoute: PageIndex.mainHealthPage,
            theme: ThemeData(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
            ),
            debugShowCheckedModeBanner: false,
            title: 'jcring health',
            // 支持的国际化语言
            localeResolutionCallback: (locale, supportedLocales) {
              S.loadLang(context, S.getLangFileName(locale!), () {
                DartLog.i(_tag, '语言加载成功locale.languageCode 系统语言：${locale.languageCode}_${locale.countryCode} language：${S.language} calendarLanguage：${S.calendarLanguage}');
                EventBusUtil.getInstance().fire(DataEvent(HealthDataType.REFRESH_READLANGFINISH, <String, String>{}));
              });
              return supportedLocales.first;
            }));
  }
}
